import jsRsasign from 'jsrsasign';
import {
	jwtPrivateKey
} from "@/config.js";
const getSignCode = function(msg) {
	// 创建RSAKey对象
	let rsa = new jsRsasign.RSAKey();
	//因为后端提供的是pck#8的秘钥对，所以这里使用 KEYUTIL.getKey来解析秘钥
	let signPrivateKey = jwtPrivateKey;
	// 将密钥转码,其实就是将头部尾部默认字符串去掉
	signPrivateKey = jsRsasign.KEYUTIL.getKey(signPrivateKey);
	// 创建Signature对象，设置签名编码算法
	// alg:对应的是规则 需要和后端统一
	let sig = new jsRsasign.KJUR.crypto.Signature({
		"alg": "SHA256withRSA",
		"prov": "cryptojs/jsrsa",
		"prvkeypem": signPrivateKey
	});
	// 初始化
	sig.init(signPrivateKey)
	// 传入待加密字符串
	sig.updateString(msg);
	// 生成密文
	let sign = jsRsasign.hextob64(sig.sign());
	return sign
}
const jwtSign = (data) => {
	let header = {
		"alg": "RS256",
		"typ": "JWT"
	};
	header = JSON.stringify(header);
	header = new Buffer(header).toString('base64');
	header = header.replaceAll('+', '-');
	header = header.replaceAll('/', "_");
	header = header.replaceAll('=', '');

	data = JSON.stringify(data);
	data = new Buffer(data).toString('base64');
	data = data.replaceAll('+', '-');
	data = data.replaceAll('/', "_");
	data = data.replaceAll('=', '');
	
	let fullData = header + '.' + data;
	fullData = getSignCode(fullData);
	fullData = fullData.replaceAll('+', '-');
	fullData = fullData.replaceAll('/', "_");
	fullData = fullData.replaceAll('=', '');
	let res = header + '.' + data + '.' + fullData;
	return res;
}

export default jwtSign;
